package com.doge.service.admin.promotion;

import com.alibaba.druid.util.StringUtils;
import com.doge.bean.base.BaseData;
import com.doge.bean.base.BaseParam;
import com.doge.bean.pojo.ad.Ad;
import com.doge.bean.pojo.ad.AdExample;
import com.doge.mapper.AdMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * promotion板块是负责管理推广模块
 * AdServiceImpl是广告板块管理
 * Created By ntian
 */
@Service
public class AdServiceImpl implements AdService{
    @Autowired
    AdMapper adMapper;

    /**
     * list所有的广告
     * @param name 广告标题
     * @param content 广告内容
     * @param baseParam sort order字段
     * @return 广告板块上的所有广告
     */
    @Override
    public BaseData listAllAds(String name, String content, BaseParam baseParam) {
        PageHelper.startPage(baseParam.getPage(),baseParam.getLimit());
        AdExample adExample = new AdExample();
        AdExample.Criteria criteria = adExample.createCriteria();
        //设置deleted=false(0)的时候才行显示
        criteria.andDeletedEqualTo(false);
        //如果name（广告标题）和content（广告内容不为空），那么增加上name和content的模糊查询
        if (!StringUtils.isEmpty(name)){
            criteria.andNameLike("%"+name+"%");
        }
        if (!StringUtils.isEmpty(content)){
            criteria.andContentLike("%"+content+"%");
        }
        //只要name或者content有一个为空的时候，那么直接用AdExample去进行查询
        adExample.setOrderByClause(baseParam.getSort()+" "+baseParam.getOrder());
        List<Ad> adList = adMapper.selectByExample(adExample);
        PageInfo pageInfo = new PageInfo(adList);
        long total = pageInfo.getTotal();
        return BaseData.list(adList,total);
    }

    @Override
    public int createAdList(Ad ad) {
        ad.setAddTime(new Date());
        AdExample adExample = new AdExample();

        int rows = adMapper.insertSelective(ad);
        return rows;
    }

    @Override
    public int updateAd(Ad ad) {
        int rows = adMapper.updateByPrimaryKeySelective(ad);
        return rows;
    }

    @Override
    public int deleteAd(Ad ad) {
        ad.setDeleted(true);
        int rows = adMapper.updateByPrimaryKeySelective(ad);
        return rows;
    }
}